import { Button, View, ScrollView, Image } from "@tarojs/components";
import Taro, { useDidHide, useUnload } from "@tarojs/taro";
import clsx from "clsx";
import { useRef, useState } from "react";
import playon from "@/as/icon_ai_voice_on.png";

const rmOpt: Taro.RecorderManager.StartOption = {
  duration: 10000,
  sampleRate: 44100,
  numberOfChannels: 1,
  encodeBitRate: 192000,
  format: "aac",
  frameSize: 50,
};

export default function Index() {
  const [status, setStatus] = useState<"inactive" | "recording">("inactive");
  const rm = useRef<Taro.RecorderManager>();
  const iac = useRef<Taro.InnerAudioContext>();
  const raFrame = useRef<number>();
  const [time, setTime] = useState<string>("00:00:000");
  const [files, setFiles] = useState<string[]>(
    Taro.getStorageSync("files") || []
  );

  const start = () => {
    if (!rm.current) {
      console.log("创建录音");
      const _rm = Taro.getRecorderManager();
      // _rm.onFrameRecorded((res) => {
      //   console.log(res);
      // });
      _rm.onStart(() => {
        console.log("start");
        setStatus("recording");
        cnow();
      });
      _rm.onStop(async (res) => {
        setFiles((f) => {
          const newFiles = [res.tempFilePath, ...f];
          Taro.setStorageSync("files", newFiles);
          return newFiles;
        });
      });
      rm.current = _rm;
    }

    if (status === "inactive") {
      rm.current.start(rmOpt);
    }

    if (status === "recording") {
      rm.current.stop();
      setStatus("inactive");
      if (raFrame.current) {
        cancelAnimationFrame(raFrame.current);
      }
    }
  };

  const remove = (path: string) => {
    const newFiles = files.filter((p) => p !== path);
    setFiles(newFiles);
    Taro.setStorageSync("files", newFiles);
  };

  useDidHide(() => {
    clear();
  });

  useUnload(() => {
    clear();
  });

  const clear = () => {
    console.log("清理");
    if (raFrame.current) {
      cancelAnimationFrame(raFrame.current);
    }
    if (status === "recording") {
      if (rm.current) {
        rm.current.stop();
      }
    }

    if (iac.current) {
      iac.current.stop();
      iac.current.destroy();
    }
  };

  const cnow = () => {
    if (raFrame.current) {
      cancelAnimationFrame(raFrame.current);
    }

    const start = Date.now();
    function _run() {
      const now = Date.now() - start;
      // console.log(formatTime(now));
      setTime(formatTime(now));
      raFrame.current = requestAnimationFrame(_run);
    }
    _run();
  };

  const play = (path: string) => {
    if (!iac.current) {
      console.log("创建播放");
      const _iac = Taro.createInnerAudioContext();
      _iac.volume = 1;
      // _iac.onPlay(() => {
      //   console.log("开始播放");
      //   console.log(_iac.duration);
      // });
      // _iac.onTimeUpdate(() => {
      //   console.log(_iac.currentTime);
      // });
      iac.current = _iac;
    }
    // let url =
    //   "https://bbs-xk.oss-cn-chengdu.aliyuncs.com/rb9lxihRTTOOcdd4b88e19d05152de05bd2a4991413d.mp3";

    iac.current.stop();
    iac.current.src = path;
    //注意，手机调整为静音。无法播放出声音
    iac.current.play();
  };

  const shareWx = (path: string) => {
    Taro.shareFileMessage({
      filePath: path,
      success: (res) => {
        console.log(res);
      },
      fail: (err) => {
        console.log(err);
      },
    });
  };

  return (
    <View className="bg-[#e8e8e8] h-screen flex flex-col">
      <ScrollView
        className="flex-1"
        style={{ height: 200 }}
        scrollY
        scrollWithAnimation
      >
        <View className="p-4 space-y-4">
          {files.map((f) => (
            <View className="rounded-md overflow-hidden">
              <ScrollView className="w-full" scrollX>
                <View className="flex w-[120%]">
                  <View className="bg-[#928c81] w-5/6 flex items-center text-white text-xs p-2">
                    <Image
                      src={playon}
                      className="w-7 h-7"
                      onClick={() => play(f)}
                    />
                    <View className="flex-1 truncate px-2">{f}</View>
                    <Button
                      className={"text-xs py-1 !bg-[#74503d]  shadow"}
                      onClick={() => shareWx(f)}
                      type="primary"
                    >
                      转发到微信
                    </Button>
                  </View>
                  <View
                    className="bg-yellow-500 w-1/6 flex items-center justify-center text-yellow-50"
                    onClick={() => remove(f)}
                  >
                    删除
                  </View>
                </View>
              </ScrollView>
            </View>
          ))}
        </View>
      </ScrollView>

      <View className={clsx("bg-[#918f8e] px-4 pb-16 pt-4")}>
        <View
          className={clsx(
            "text-center text-yellow-400 max-h-0 overflow-hidden",
            "transition-[max-height] duration-300",
            { "!max-h-32": status === "recording" }
          )}
        >
          {time}
        </View>

        <Button
          className={clsx(
            "w-20 h-20 bg-[#d42a02] rounded-full text-slate-300",
            "text-xs flex items-center justify-center mt-2"
          )}
          style={{
            boxShadow:
              "10rpx 3rpx 10rpx rgba(0, 0, 0, 0.377), 2rpx 2rpx 10rpx 0rpx inset #fb702c, -4rpx -4rpx 2rpx 0rpx inset #d42a02",
          }}
          onClick={start}
        >
          {status === "recording" ? "停止" : "点击录音"}
        </Button>
      </View>
    </View>
  );
}

function formatTime(milliseconds: number) {
  const seconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const secondsRemaining = seconds % 60;
  const millisecondsRemaining = milliseconds % 1000;

  return `${minutes.toString().padStart(2, "0")}:${secondsRemaining
    .toString()
    .padStart(2, "0")}.${millisecondsRemaining.toString().padStart(3, "0")}`;
}
